package kxfang.com.main.ui;

import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.utils.TextUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;


import java.util.logging.Logger;

import kxfang.com.base.activity.MvvmBaseActivity;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.base.viewmodel.IMvvmBaseViewModel;
import kxfang.com.common.bean.NewQuanModel;
import kxfang.com.common.bean.OrderPayModel;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.dialog.WaitDialog;
import kxfang.com.common.parameter.OrderPar;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.utils.HawkUtil;
import kxfang.com.common.utils.PayUtil;
import kxfang.com.common.utils.RouterUtils;
import kxfang.com.common.utils.StatusBarUtil;
import kxfang.com.common.views.dialog.PayDialog;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;
import kxfang.com.main.R;
import kxfang.com.main.databinding.MainActivityGuideBinding;
import kxfang.com.main.databinding.MainWebviewCouponsLayoutBinding;

import static kxfang.com.common.router.RoutHub.COUPONS_MAIN;


/**
 * Created by ZJ
 * on 2020/5/14
 * Class Content 优惠券web页面
 */
@Route(path = COUPONS_MAIN)
public class CouponsWebActivity extends MvvmBaseActivity<MainWebviewCouponsLayoutBinding, IMvvmBaseViewModel> implements PayDialog.PayListener {


    private WebSettings webSettings;

    private PayDialog dialog;
    private long beforeTime = 0;// 防止多次点击
    private int payType;//支付方式
    private PayUtil payUtil;// 支付版块
    //    private QuanModel.ListsBean.GroupBean dataModel;
    private NewQuanModel dataModel;
    private int myType = 0;
    private WaitDialog.Builder waitDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTopActivityView(this, viewDataBinding.topView, R.color.common_color_2947);
        waitDialog = new WaitDialog.Builder(this);
        waitDialog.setMessage("加载中").show();
        initView(getIntent().getExtras().getString("url"));
        viewDataBinding.topContent.setText(getIntent().getExtras().getString("title"));
        viewDataBinding.webBack.setOnClickListener(v -> finish());
        viewDataBinding.tvDescription.setOnClickListener(view1 -> {
            Intent intent = new Intent(this, OtherWebVIewActivity.class);
            intent.putExtra("url", Constant.LOAD_WEBVIEWURL.concat("/cpDescription.html?type=mobile"));
            startActivity(intent);

        });
    }

    @Override
    protected IMvvmBaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.main_webview_coupons_layout;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    private void initView(String url) {
        webSettings = viewDataBinding.webView.getSettings();
        viewDataBinding.webView.clearCache(true);
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
//        webView.addJavascriptInterface(new test(this), "test");
        viewDataBinding.webView.addJavascriptInterface(this, "test");
        viewDataBinding.webView.loadUrl(url);
        viewDataBinding.webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                viewDataBinding.webView.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                waitDialog.dismiss();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    webView.getSettings()
//                            .setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//                }
                // 接受所有网站的证书
                handler.proceed();
            }
        });
    }

    @JavascriptInterface
    public void userLogin() {
        if (HawkUtil.getUserId() == null) {
            ToastUtils.showShort("您还没有登录");
            return;
        }
    }

    //跳转店铺使用
    @JavascriptInterface
    public void goUse(String id) {
//        Intent intent = new Intent(this, HomeStoreDetailFragment.class);
//        intent.putExtra("id", id.substring(1,id.length()-1));
//        startActivity(intent);

    }


    //购买平台代金券
    @JavascriptInterface
    public void goBuy(String param) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - beforeTime < 1000) {
            ToastUtils.showShort("操作太频繁");
            return;
        }
        beforeTime = currentTime;
        CouponsWebActivity.this.runOnUiThread(new Runnable() {
            public void run() {

                dataModel = new Gson().fromJson(param, NewQuanModel.class);
                myType = 1;
                showPayDialog();

            }
        });
    }

    //购买商家代金券
    @JavascriptInterface
    public void buying(String param) {

        long currentTime = System.currentTimeMillis();
        if (currentTime - beforeTime < 1000) {
            ToastUtils.showShort("操作太频繁");
            return;
        }
        beforeTime = currentTime;
        CouponsWebActivity.this.runOnUiThread(new Runnable() {
            public void run() {

                dataModel = new Gson().fromJson(param, NewQuanModel.class);
                myType = 2;
                showPayDialog();

            }
        });
    }


    /**
     * 显示支付对话框
     */
    private void showPayDialog() {
        dialog = new PayDialog(this, this, String.valueOf(dataModel.getOrderPrice()));
        dialog.showAtLocation(viewDataBinding.mainLayout, Gravity.CENTER, 0, 0);
    }

    @Override
    public void onPay(int type) {
        OrderPar pay = new OrderPar();

        if (myType == 1) {
            pay.setOrderType(8);
        }
        if (myType == 2) {
            pay.setCompanyID(dataModel.getCompanyID());
            pay.setGoodsID(dataModel.getGoodsID());
            pay.setOrderType(dataModel.getOrderType());
        }
        pay.setGoodsMealID(dataModel.getGoodsMealID());
        pay.setOrderPrice(String.valueOf(dataModel.getOrderPrice()));
        pay.setPayType(type);
        pay.setOrginalPrice(String.valueOf(dataModel.getOrginalPrice()));
        pay.setRUserID(String.valueOf(HawkUtil.getUserId()));
        EasyHttp.post(HttpConfig.addOrder)
                .cacheKey(HttpConfig.addOrder)
                .upJson(GsonUtils.toJson(pay))
                .execute(new SimpleCallBack<OrderPayModel>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onSuccess(OrderPayModel orderPayModel) {
                        payType = type;
                        onPay(orderPayModel);
                    }
                });

    }

    private void onPay(OrderPayModel model) {
        payUtil = new PayUtil(this, payType, false, model, new PayUtil.PayListener() {
            @Override
            public void onWxSuccess(boolean isSuccess) {
                if (!isSuccess) {
//                    Navigate.push(instance, OrderDetailFragment.class, model.getOrderNo());
//                    Navigate.pop(instance, true);
                } else {
                    ToastUtils.showShort("购买成功");
                }
                finish();
            }

            @Override
            public void onAliSuccess(boolean isSuccess) {
                if (!isSuccess) {
//                    Navigate.push(instance, OrderDetailFragment.class, model.getOrderNo());
//                    Navigate.pop(instance, true);
                } else {
                    ToastUtils.showShort("购买成功");
                }
                finish();
            }

            @Override
            public void onUpdateStatus() {
//                Navigate.push(instance, OrderDetailFragment.class, model.getOrderNo());
//                Navigate.pop(instance, true);
            }
        });
    }

    /**
     * 释放支付相关内容
     */
    public void release() {
        if (payUtil != null) {
            payUtil.clearDisposable();
        }
    }


}
